package com.itheima.fanout_optimize;

import com.itheima.utils.RabbitMqUtil;
import com.rabbitmq.client.*;

import java.io.IOException;


/**
 * @author Administrator
 */
public class Consumer2 {

    /**
     * 定义队列2(queue)
     */
    private static final String FANOUT_QUEUE_OPTIMIZE_2 = "fanout_queue_optimize_2";

    /**
     * 定义交换机
     */
    private static final String FANOUT_EXCHANGE_OPTIMIZE= "fanout_exchange_optimize";

    public static void main(String[] args) throws Exception {

        //获取连接
        Connection connection = RabbitMqUtil.newConnection();

        //3.创建频道(信道)
        Channel channel = connection.createChannel();

        //4.创建队列
        channel.queueDeclare(FANOUT_QUEUE_OPTIMIZE_2, true, false, false, null);

        //创建交换机
        channel.exchangeDeclare(FANOUT_EXCHANGE_OPTIMIZE,BuiltinExchangeType.FANOUT);

        //绑定交换机
        channel.queueBind(FANOUT_QUEUE_OPTIMIZE_2,FANOUT_EXCHANGE_OPTIMIZE,"");

        //一次只能接收并处理一个消息
        channel.basicQos(1);


        //创建消费者；并设置消息处理
        DefaultConsumer consumer = new DefaultConsumer(channel) {

            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                //路由key
                System.out.println("路由key为：" + envelope.getRoutingKey());
                //交换机
                System.out.println("交换机为：" + envelope.getExchange());
                //消息id
                System.out.println("消息id为：" + envelope.getDeliveryTag());
                //收到的消息
                System.out.println("Consumer2接收到的消息为：" + new String(body, "UTF-8"));


                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                /**
                 * basicAck(long deliveryTag, boolean multiple)
                 * 参数1 deliveryTag :消息id
                 * 参数2 multiple :表示是否支持批量确认机制以减少网络流量
                 *
                 *手动确认消息
                 */
                channel.basicAck(envelope.getDeliveryTag(),false);

            }

        };

        //监听消息
        /**
         * basicConsume(String queue, boolean autoAck, Consumer callback)
         * 参数1 queue：队列名称
         * 参数2 autoAck：是否自动确认，设置为true为表示消息接收到自动向mq回复接收到了，mq接收到回复会删除消息，设置为false则需要手动确认
         * 参数3 callback ：消息接收到后回调
         */
        channel.basicConsume(FANOUT_QUEUE_OPTIMIZE_2, false, consumer);

    }


}
